#!/usr/bin/env node

var fs    = require('fs')
var join  = require('path').join
var spawn = require('child_process').spawn


const QEMU_SYSTEM = 'qemu-system-'


var link = fs.readlinkSync('out/latest').split('/');

var cpu_family = link[link.length-2]
var platform   = link[link.length-1]

var type = platform.split('_')[1]

var machine
switch(cpu_family)
{
  case 'arm':
    machine = 'versatilepb'
  break
}


var command = QEMU_SYSTEM+cpu_family

var args =
[
  '-enable-kvm',
  '-vga', 'std',
  '-m', '256M',
  '-redir', 'tcp:50080::80',
  '-redir', 'tcp:50443::443'
]

const outDir = join('out', cpu_family, platform)
switch(type)
{
  case 'img':
    args.push('-hda', join(outDir, 'rootfs'))
    args.push('-hdb', join(outDir, 'usersfs'))
  break

  case 'iso':
    args.push('-cdrom', join(outDir, 'rootfs'))
    args.push('-hdb'  , join(outDir, 'usersfs'))
  break

  case 'qemu':
    var append =
    [
      'root=/dev/sda',
      'ip=dhcp'
    ]

    switch(process.argv[2])
    {
      case 'nographic':
        append.push('console=ttyS0')  // redirect to terminal
        args.push('-nographic')
      break

      case 'curses':
        append.push('vga=extended')  // 80x50
        args.push('-curses')
      break

      default:
        append.push('vga=0x344')  // 1024x768x32
    }

    args.push('--kernel', join(outDir, 'barebones'))
    args.push('--initrd', join(outDir, 'initramfs'))
    args.push('-hda',     join(outDir, 'usersfs'))
    args.push('-append', append.join(' '))
  break

  default:
    throw 'Unknown platform "'+platform+'"'
}

if(machine) args.unshift('-machine', machine)

// check if kvm is supported
var kvm = /(vmx|svm)/;
var contents = "";

try
{
  contents = fs.readFileSync('/proc/cpuinfo');
} catch(e){
  throw(e);
}

if(kvm.test(contents) === false)
{
  // disable kvm
  console.log("Your computer does not support kvm. NodeOS will be slower without it.");
  args.shift();
}

spawn(command, args, {stdio: 'inherit'})
.on('error', console.trace.bind(console));
